using System;
using System.Web;
using System.Diagnostics;
using CKS.EBE.API;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace CKS.EBE
{
    public class SharePointUrlProvider : IUrlProvider
    {
        #region IUrlProvider Members

        public bool UrlHandled(string sUrl)
        {
            // TO DO : change path
            return sUrl.ToLower().Contains("/lists/posts/");
        }

        public void RewriteUrl(Uri siteUrl, HttpContext context, SPWeb oWeb, BlogSettings bs)
        {
            if (oWeb.Features[BlogContext.BlogFeatureGUID] == null) return;

            string sUrl = siteUrl.ToString().ToLower();

            HttpContext.Current.Items["ebeRewrittenPath"] = sUrl;

            string sPartial = sUrl.Substring(oWeb.Url.Length);
            //string sPageName = siteUrl.Segments[siteUrl.Segments.Length - 1];

            Debug.WriteLine("Rewriting Url: " + sUrl);

            if (sPartial.StartsWith("/lists/" + Localization.GetResource("blogcatagories_Folder", "core").ToLower() + "/category.aspx?"))
            {
                RewriteTagUrl(context, oWeb);
            }   
            else if (sPartial.StartsWith("/lists/" + Localization.GetResource("blogpost_Folder", "core").ToLower() + "/post.aspx"))
            {
                RewritePostUrl(siteUrl, context, oWeb);
            }
        }

        private static void RewriteTagUrl(HttpContext context, SPWeb oWeb)
        {
            //context.RewritePath(oWeb.ServerRelativeUrl + "/Category.aspx" + sQuery + "c=" + m.Groups["title"].Value);
            context.RewritePath(SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, "/archives/tags/" + context.Request["Name"] + "/default.aspx"));
        }

        public SPListItem GetPostFromUrlTitle(string urlTitle, SPWeb oWeb)
        {
            SPList oList = Helper.GetListByFolderName(oWeb, Localization.GetListName(Localization.BlogList.Posts, oWeb.Language));

            SPQuery query = new SPQuery();
            query.Query = string.Format("<Where><Eq><FieldRef Name='BlogTitleForUrl'/><Value Type='Text'>{0}</Value></Eq></Where>", urlTitle);

            SPListItemCollection col = oList.GetItems(query);

            if (col.Count > 0) return col[0];

            return null;
        }

        public void RewritePostUrl(Uri siteUrl, HttpContext context, SPWeb oWeb)
        {
            context.RewritePath(SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, "/Post.aspx?id=" + context.Request["id"]));
        }

        public string createTagUrl(string tag)
        {
            return SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/archive/tags/" + tag + "/default.aspx");
        }

        public string createMonthUrl(string postDate)
        {
            return SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/archive/" + postDate.Substring(0, 4) + "/" + postDate.Substring(5, 2) + ".aspx");
        }

        public string createPostUrl(string postDate, string urlTitle, string postID)
        {
            return SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/lists/" + Localization.GetResource("blogpost_Folder", "core").ToLower() + "/post.aspx?");
        }

        public string createAbsolutePostUrl(string postDate, string urlTitle, string postID)
        {
            return SPUrlUtility.CombineUrl(SPContext.Current.Web.Url, "/lists/" + Localization.GetResource("blogpost_Folder", "core").ToLower() + "/post.aspx?");
        }

        public void CheckRootUrl(Uri siteUrl, HttpContext context, SPWeb oWeb)
        {
            if (oWeb.Features[BlogContext.BlogFeatureGUID] == null) return;

            BlogSettings bs = new BlogSettings(oWeb);

            string sUrl = siteUrl.ToString().ToLower();
            if (sUrl.Contains("?")) sUrl = sUrl.Substring(0, sUrl.IndexOf("?"));

            if (!sUrl.EndsWith("/") && !sUrl.EndsWith(".aspx")) sUrl += "/";

            if ((sUrl.Length - oWeb.Url.Length <= 1) || (sUrl.StartsWith(oWeb.Url.ToLower() + "/default.aspx")))
            {
                HttpContext.Current.Items["ebeRewrittenPath"] = sUrl;
                Debug.WriteLine("Rewriting: " + oWeb.ServerRelativeUrl + "/" + bs.HomePage);
                context.RewritePath(SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, "/" + bs.HomePage));
            }
        }

        #endregion
    }
}
